/**
 * 使用store.dispatch('modules/module')可以触发store里面的actions操作
 * eg: action_name({ commit, state }) { ....content }
 *
 * 使用store.commit('mutations',param)可以触发store里面的mutations操作
 * eg: this.store.commit('mutations',param)
 */

import { getToken, setToken, removeToken, getUser, setUser, removeUser, getRoles, setRoles, removeRoles } from '@/utils/cookies'
import { resetRouter } from '@/router'

const state = {
    token: getToken(),
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    roles: getRoles() && getRoles() !== 0 ?JSON.parse(getRoles()):[],
    user: getUser() && getUser() !== 0 ? JSON.parse(getUser()) : ''
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
        setToken(token)
    },
    SET_USER: (state, user) => {
        setUser(user)
        state.user = user
    },
    SET_ROLE: (state, roles) => {
        setRoles(roles)
        state.roles = roles
    },
    LOGOUT: (state) => {
        console.debug("logout to clear anything")
        state.token = ''
        state.roles = []
        state.user = ''
        removeUser()
        removeToken()
        resetRouter()
        removeRoles()
    }
}

const actions = {
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            let r = commit('LOGOUT')
            resolve(r)
            //todo api logout
        })
    }
}

export default {
    state,
    mutations,
    actions
}

